package cn.ffcs.businessrequest.service;

import java.io.File;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;

import cn.ffcs.businessrequest.dao.IReqDocuDAO;
import cn.ffcs.businessrequest.model.DocContent;
import cn.ffcs.businessrequest.model.ProdAdvReq;
import cn.ffcs.businessrequest.model.ReqDocu;
import cn.ffcs.base.service.BaseService;
import cn.ffcs.common.model.Attach;
import cn.ffcs.system.dict.model.Dict;
import cn.ffcs.system.dict.service.DictService;

/**
 * 业务需求交互单服务层<br/>
 * <table>
 * <tr>
 * <td>负责人/principal:</td>
 * <td colspan="2">pany</td>
 * <tr>
 * <td>修改记录/revision:</td>
 * <td colspan="2"></td>
 * </tr>
 * <tr>
 * <td>日期:</td>
 * <td>修改人:</td>
 * <td>修改说明:</td>
 * </tr>
 * <tr>
 * <td></td>
 * <td></td>
 * <td></td>
 * </tr>
 * </table>
 * @author pany
 * @version $Id$
 */
public class ProdAdvReqService<D extends ProdAdvReq> extends BaseService<D> implements IProdAdvReqService<D>
{
    private static final int BUFFER_SIZE = 512 * 1024;
    

    /** 文档DAO **/
    private IReqDocuDAO reqDocuDAO;

    /** 文档内容服务 **/
    private IDocContentService docContentService;
    /** 字典服务 **/
    private DictService<Dict> dictService;

    /**
     * 分解需求单保存
     * TODO 请输入方法说明
     * @param prodAdvReq
     * @param oldProdAdvReqId
     * @return
     */
    public boolean saveProdAdvReq(D prodAdvReq,String oldProdAdvReqId){
        ///将原需求单结束，附件复制一份给新需求单
        D oldProdAdvReq = super.findById(new Integer(oldProdAdvReqId));
        oldProdAdvReq.setTranStatus("PROD");
        oldProdAdvReq.setOpType("FJ");
        oldProdAdvReq.setEnd(super.getCurrSysdate());
        super.saveOrUpdate(oldProdAdvReq);
        // 保存产品资料数据
        prodAdvReq.setOpType("FJ");
        prodAdvReq.setChildAreq(oldProdAdvReq.getId()+"");
        super.saveOrUpdate(prodAdvReq);     //生成新的合并需求单
        Criterion cond1 = Restrictions.eq("refEntity", oldProdAdvReq.getClass()
                .getName());
        Criterion cond2 = Restrictions.eq("refEntityId", oldProdAdvReqId);
        Criterion condAttach = Restrictions.and(cond1, cond2);
        List<ReqDocu> reqDocus = reqDocuDAO.findBy(condAttach);
        for (ReqDocu reqDocu : reqDocus)
        {
            ReqDocu tmp = new ReqDocu();
            tmp.setContent(reqDocu.getContent());
            tmp.setName(reqDocu.getName());
            tmp.setBegin(reqDocu.getBegin());
            tmp.setCreator(reqDocu.getCreator());
            tmp.setDocType(reqDocu.getDocType());
            tmp.setEnd(reqDocu.getEnd());
            tmp.setFullName(reqDocu.getFullName());
            tmp.setName(reqDocu.getName());
            tmp.setPrefix(reqDocu.getPrefix());
            tmp.setRefEntity(reqDocu.getRefEntity());
            tmp.setRefEntityId(reqDocu.getRefEntityId());
            tmp.setVersion(reqDocu.getVersion());
            tmp.setProcessDetail(reqDocu.getProcessDetail());
            reqDocuDAO.save(tmp);
        }
        return true;
    }
    
    public boolean saveProdAdvReq(D prodAdvReq,String [] oldProdAdvReqs){
        // 保存产品资料数据
        super.saveOrUpdate(prodAdvReq);     //生成新的合并需求单
        D oldProdAdvReq;
        for(String oldId:oldProdAdvReqs ){
            ///将原需求单结束，附件复制一份给新需求单
            oldProdAdvReq=super.findById(new Integer(oldId));
            oldProdAdvReq.setChildAreq(prodAdvReq.getId()+"");
            oldProdAdvReq.setTranStatus("PROD");
            oldProdAdvReq.setOpType("HB");
            super.saveOrUpdate(oldProdAdvReq);
            Criterion cond1 = Restrictions.eq("refEntity", oldProdAdvReq
                    .getClass().getName());
            Criterion cond2 = Restrictions.eq("refEntityId", oldProdAdvReq
                    .getId().toString());
            Criterion condAttach = Restrictions.and(cond1, cond2);
            List<ReqDocu> reqDocus = reqDocuDAO.findBy(condAttach);
            for(ReqDocu reqDocu:reqDocus){
                ReqDocu tmp=new ReqDocu();
                tmp.setContent(reqDocu.getContent());
                tmp.setName(reqDocu.getName());
                tmp.setBegin(reqDocu.getBegin());
                tmp.setCreator(reqDocu.getCreator());
                tmp.setDocType(reqDocu.getDocType());
                tmp.setEnd(reqDocu.getEnd());
                tmp.setFullName(reqDocu.getFullName());
                tmp.setName(reqDocu.getName());
                tmp.setPrefix(reqDocu.getPrefix());
                tmp.setRefEntity(reqDocu.getRefEntity());
                tmp.setRefEntityId(reqDocu.getRefEntityId());
                tmp.setVersion(reqDocu.getVersion());
                tmp.setProcessDetail(reqDocu.getProcessDetail());
                reqDocuDAO.save(tmp);
            }
        }
        return true;
    }
    
    /**
     * 保存产品资料操作
     */
    @SuppressWarnings("unchecked")
    public boolean saveProdAdvReq(D prodAdvReq, List<File> uploads,
            List<String> fileNames, String[] reqDocuIDs, String[] delIDs)
    {
        // 保存产品资料数据
        super.saveOrUpdate(prodAdvReq);

        // 保存附件
        if (uploads != null)
        {
            int i = 0;
            for (i = 0; i < uploads.size(); i++)
            {
                try
                {
                    File file = uploads.get(i);
                    if(file!=null){
                        byte[] result = new byte[BUFFER_SIZE];
                        result = FileUtils.readFileToByteArray(file);
                        FileUtils.forceDelete(file);
    
                        String fileName = fileNames.get(i);
                        String fullName = fileName;
                        String name = fullName.substring(0, fullName.indexOf("."));
                        String prefix = fullName.substring(
                                fullName.indexOf(".") + 1, fullName.length());

                        ReqDocu reqDocu = new ReqDocu();

                        Dict dict = null;
                        if (reqDocuIDs[i] != null && !reqDocuIDs[i].equals("")){
                            Criterion dtcond = Restrictions.eq("keyValue", reqDocuIDs[i]);
                            List<Dict> list = dictService.findBy(dtcond)==null ? null : dictService.findBy(dtcond);
                            dict = list.get(0);
                        }
                        DocContent doc=new DocContent();
                        doc.setContent(result);
                        docContentService.saveOrUpdate(doc);
                        reqDocu.setContent(doc);
                        reqDocu.setDocType(dict);
                        reqDocu.setFullName(fullName);
                        reqDocu.setName(name);
                        reqDocu.setPrefix(prefix);
                        reqDocu.setRefEntity(prodAdvReq.getClass().getName());
                        reqDocu.setRefEntityId(prodAdvReq.getId().toString());
                        // 设置基本信息
                        setBaseInfo(reqDocu);
    
                        reqDocuDAO.save(reqDocu);
                    }
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }

        // 删除附件
        if (delIDs != null && delIDs.length > 0)
        {
            for (String id : delIDs)
            {
                reqDocuDAO.deleteById(id);
            }
        }
        return true;
    }
    
    /**
     * 删除操作
     * @param baseEntity
     */
    public void remove(D prodAdvReq)
    {
        if (prodAdvReq != null)
        {
            Criterion cond1 = Restrictions.eq("refEntity", prodAdvReq
                    .getClass().getName());
            Criterion cond2 = Restrictions.eq("refEntityId", prodAdvReq
                    .getId().toString());
            Criterion condAttach = Restrictions.and(cond1, cond2);
            List<ReqDocu> reqDocus = reqDocuDAO.findBy(condAttach);
            for (ReqDocu docu : reqDocus)
            {
                reqDocuDAO.deleteById(docu.getId() + "");
            }
            super.remove(prodAdvReq);
        }
    }

    public IDocContentService getDocContentService()
    {
        return docContentService;
    }

    public void setDocContentService(IDocContentService docContentService)
    {
        this.docContentService = docContentService;
    }

    public IReqDocuDAO getReqDocuDAO()
    {
        return reqDocuDAO;
    }

    public void setReqDocuDAO(IReqDocuDAO reqDocuDAO)
    {
        this.reqDocuDAO = reqDocuDAO;
    }

    public DictService<Dict> getDictService()
    {
        return dictService;
    }

    public void setDictService(DictService<Dict> dictService)
    {
        this.dictService = dictService;
    }
}
